const { Result } = require('../lib/entity.js');
const Controller = function(name){
    this.name =  name;
    this.doAction = function(mappingUrl,requestUrl,request,response){
        // do nothing
    };
};
const InitContext = function(){
    this.doInit = function(){
        return new Promise(function(resolve, reject){
            resolve(new Result(true,"ok"));
        });
    }
}
const InitContextFinder = function(){
  this.findInitContext = function(cname){
      return null;
  }  
};
const ActionHandler = function(func){
  this.doAction = func;  
};
const ControllerFinder = function(){
  this.findController = function(cname){
      return null;
  }  
};
const FilterFinder = function(){
  this.findFilter = function(cname){
      return null;
  }
};
const Filter = function(name){
    this.name = name;
    this.doFilter = function(request,response){
        return new Promise(function(resolve, reject){
            resolve(true);
        });
    }
}
function parseValueWithIndex(urls,index){
    if(urls.length <= index){
        return new Result(false,"没有数据了");
    }
    let url = urls[index];
    
    let nextIndex = index+1;
    if(url){
        return new Result(true,{
            "urlNextIndex":nextIndex,
            "url":url
        });
    }else{
        return parseValueWithIndex(urls,nextIndex);
    }
}

const UrlAdapter = function(){
    this.adapter = function(reqUrl,mappingUrl){
        var urls = reqUrl.split("/");
        var murls = mappingUrl.split("/");
        let urlIndex = 0 ;
        
        var retFlag = false;
        for(var mix in murls){
            var murl = murls[mix];
            if(!murl){
                continue;
            }
            if(murl=="*" || murl=="**"){
                return true;
            }
            var result =  parseValueWithIndex(urls,urlIndex);
            
            if(!result.isSuccess()){
                return false;
            }
            var robj = result.obj;
            
            urlIndex = robj.urlNextIndex;
            if(robj.url == murl){
                retFlag = true;
            }else{
                if(robj.url.split(".")[0] == murl.split[0]){
                     retFlag = true;
                }else{
                    return false;
                }
            }
        }
        var result =  parseValueWithIndex(urls,urlIndex);
        if(result.isSuccess()){
            return false;
        }
        return retFlag;
    };
};

module.exports = {
    Controller:Controller,
    ActionHandler:ActionHandler,
    Filter:Filter,
    UrlAdapter:UrlAdapter,
    FilterFinder:FilterFinder,
    ControllerFinder:ControllerFinder,
    InitContext:InitContext,
    InitContextFinder:InitContextFinder
};